package mk.company.fin.service;

import java.net.URL;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.swing.Icon;
import javax.swing.ImageIcon;

import mk.company.fin.FinConstants;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Repository for manipulating with the local (static) files.
 * 
 * @author vlado.gjorgjiev
 */
@Service
public class IconService {

	@Autowired
	private LocaleService localeService;
	
	@Autowired
	private MessageService messageService;
	
	private Map<String, Icon> cache;
	
	
	private IconService() {
		cache = new HashMap<String, Icon>(FinConstants.Caching.ICON_FACTORY_CACHE_SIZE + 1);
	}
	
	public Icon getIcon(String messageCode) {
		Icon result = null;
		Locale locale = localeService.getCurrentLocale();
		String key = createCacheKey(messageCode, locale);
		result = cache.get(key);
		
		if (result == null) {
			URL targetUrl = messageService.getMessageAsUrl(messageCode);
			if (targetUrl != null) {
				result = new ImageIcon(targetUrl);
				if (cache.size() < FinConstants.Caching.ICON_FACTORY_CACHE_SIZE) {
					cache.put(key, result);
				}
			}
		}
		return result;
	}
	
	private String createCacheKey(String messageCode, Locale locale) {
		return locale.toString() + "_" + messageCode;
	}
	
}
